package com.hnas.core.util;

import java.io.IOException;

import freemarker.cache.StringTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;


public class TemplateUtil {
	private static TemplateUtil templateUtil;
	private Configuration cfg;
	private StringTemplateLoader stringLoader = new StringTemplateLoader();  
	private TemplateUtil(){
//		super(DTOFoc.class,Foc.class);
		cfg = new Configuration(Configuration.VERSION_2_3_23);
		cfg.setDefaultEncoding("UTF-8");
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		cfg.setTemplateLoader(stringLoader);
	}
	
	public static TemplateUtil getInstance(){
		if(templateUtil==null){
			templateUtil = new TemplateUtil();
		}
		return templateUtil;
	}
	
	public Template getTemplate(String templateContent, String templateName){
		 Object b =  stringLoader.findTemplateSource(templateName);
		 if (null==b){			 
		       stringLoader.putTemplate(templateName,templateContent);  
		 }
		 try {
			Template template = cfg.getTemplate(templateName,"utf-8");
			return template;
		} catch (TemplateNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return null;
	}
}
